{% extends 'basic/layout/page_basic.html' %}
{% load static %}

<!-- 添加标题 -->
{% block title %}
    学生管理
{% endblock %}

<!-- 添加标题 -->
{% block css %}

{% endblock %}

<!-- 添加标题 -->
{% block content %}
    <!-- 内容01：面包屑导航 -->
    <span class="layui-breadcrumb">
      <a href="#">首页</a>
      <a href="#">学生信息</a>
      <a><b>学生管理</b></a>
    </span>

    <!-- 内容02： 查询区域 --->
    <div class="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline" style="width: 20%">
                    <label class="layui-form-label" for="q_sno"><b>学号/姓名：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="q_sno" id="q_sno" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline" style="width: 22%">
                    <label class="layui-form-label" for="q_faculty"><b>院系：</b></label>
                    <div class="layui-input-block">
                        <select id="q_faculty" name="q_faculty" lay-search="" lay-filter="q_faculty">
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline" style="width: 22%">
                    <label class="layui-form-label" for="q_major"><b>专业：</b></label>
                    <div class="layui-input-block">
                        <select id="q_major" name="q_major" lay-search="">
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <input type="checkbox" name="q_status" id="q_status" title="在校">
                </div>
                <div class="layui-inline">
                    <button type="button" id="btnQuery" class="layui-btn">
                        <i class="fa fa-search" aria-hidden="true"></i>&nbsp;查询
                    </button>
                    <button type="button" id="btnAll" class="layui-btn">
                        <i class="fa fa-bars" aria-hidden="true"></i>&nbsp; 全部
                    </button>
                    <button type="button" id="btnAdd" class="layui-btn">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i>&nbsp; 添加
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 内容03：表格区域 -->
    <div class="layui-hide" id="studentTable" lay-filter="studentTable"></div>

    <!-- 内容04: 表格中的按钮 -->
    <script type="text/html" id="tableButton">
        <a class="layui-btn layui-btn-xs" lay-event="detail">
            <i class="fa fa-ellipsis-h" aria-hidden="true"></i>&nbsp; 查看
        </a>
        <a id="btnEdit" class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
            <i class="fa fa-edit" aria-hidden="true"></i> &nbsp;编辑
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="fa fa-trash" aria-hidden="true"></i>&nbsp; 删除
        </a>
    </script>

    <!-- 内容05: 弹出层表单 -->
    <div class="layerArea" style="display: none;padding: 40px 0 0 30px ">
        <form class="layui-form" id="layerForm" lay-filter="layerForm">
            {% csrf_token %}
            <div class="layui-form-item">
                <label class="layui-form-label" for="sno"><b>学号：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="sno" name="sno" class="layui-input">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
                <label class="layui-form-label" for="name"><b>姓名：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="name" name="name" class="layui-input">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" for="gender"><b>性别：</b></label>
                <div class="layui-input-inline">
                    <select id="gender" name="gender" lay-search="">
                        <option value="">请选择</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
                <label class="layui-form-label" for="birthday"><b>出生日期：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="birthday" name="birthday" class="layui-input" placeholder="请选择日期">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>

            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" for="mobile"><b>手机号码：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="mobile" name="mobile" class="layui-input">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
                <label class="layui-form-label" for="email"><b>邮箱地址：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="email" name="email" class="layui-input">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="address"><b>家庭住址：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="address" name="address" class="layui-input" style="width:263%;">
                        <span class="error-msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" for="faculty"><b>所在院系：</b></label>
                <div class="layui-input-inline">
                    <select type="text" id="faculty" name="faculty" lay-search="" lay-filter="faculty">
                        <option value="">请选择</option>
                    </select>
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
                <label class="layui-form-label" for="major"><b>所学专业：</b></label>
                <div class="layui-input-inline">
                    <select type="text" id="major" name="major" lay-search="" lay-filter="major">
                        <option value="">请选择</option>
                    </select>
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" for="start_date"><b>入学时间：</b></label>
                <div class="layui-input-inline">
                    <input type="text" id="start_date" name="start_date" class="layui-input" placeholder="请选择日期">
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
                <label class="layui-form-label" for="status"><b>状态：</b></label>
                <div class="layui-input-inline">
                    <select type="text" id="status" name="status" lay-search="">
                        <option value="">请选择</option>
                        <option value="在校">在校</option>
                        <option value="毕业">毕业</option>
                        <option value="休学">休学</option>
                        <option value="开除">开除</option>
                    </select>
                    <span class="error-msg" style="color:red; position: absolute"></span>
                </div>
            </div>
        </form>
    </div>

{% endblock %}

<!-- 添加标题 -->
{% block js %}
    <script>

        // 定义一个全局变量Operation  1-- 添加  2-- 查看  3---修改
        let Operation = 0;
        $(function () {
            // 页面的初始化
            initPage();
            // 表格的初始化
            initTable();
            // 所有的按钮点击
            buttonClick();
        });

        // ======== 页面的初始化 =======
        function initPage() {

            // ============= 初始化element ,form ===================
            layui.use(['element', 'form', 'laydate'], function () {
                let element = layui.element;
                let form = layui.form;
                let laydate1 = layui.laydate;
                let laydate2 = layui.laydate;

                //执行一个laydate实例
                laydate1.render({
                    elem: '#birthday' //指定元素
                });

                laydate2.render({
                    elem: '#start_date',
                })
            });


            // ============== 初始化查询区域院系的下拉框============
            loadQueryFacultys();
        }

        //========= 表格的初始化 ==========
        function initTable() {

            layui.use(['table', 'form'], function () {
                let table = layui.table;
                let form = layui.form;

                // 渲染表格
                table.render({
                    elem: $('#studentTable')
                    , url: "{% url 'list_student' %}"
                    , method: 'post'
                    , where: {
                        // 携带输入的查询条件！
                        q_sno: $('#q_sno').val().trim(),
                        q_faculty: $('#q_faculty').val(),
                        q_major: $('#q_major').val(),
                        q_status: $('#q_status').is(":checked"),
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 60, title: '编号', align: 'center', sort: true}
                        , {field: 'sno', title: '学号', align: 'center',}
                        , {field: 'name', title: '姓名', align: 'center', sort: true}
                        , {field: 'gender', title: '性别', width: 80, align: 'center',}
                        , {field: 'faculty__name', title: '院系名称', align: 'center', sort: true}
                        , {field: 'major__name', title: '专业名称', align: 'center', sort: true}
                        , {field: 'status', title: '状态', align: 'center', sort: true}
                        , {fixed: 'right', title: '操作', width: '20%', align: 'center', toolbar: '#tableButton'}

                    ]]
                    , page: true  // 启用分页，默认就向后台发送两个参数：page=1,limit=10
                    , limit: 12
                    , limits: [12, 15, 20, 30, 50, 75, 100]
                    , done: function (res, current, count) {
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }

                });


                // 侦听表格的操作
                table.on('tool(studentTable)', function (obj) {
                    // 获得点击行的数据
                    let lineData = obj.data;

                    // 判断点击了什么按钮
                    if (obj.event === 'detail') {
                        // ==== 查看====
                        // 修改Operation
                        Operation = 2;
                        // 加载弹出层
                        loadLayer("查看学生详情", lineData);
                    } else if (obj.event === 'edit') {
                        // ==== 编辑====
                        // 修改Operation
                        Operation = 3;
                        // 加载弹出层
                        loadLayer("修改学生信息", lineData);
                    } else if (obj.event === 'del') {
                        //删除
                        deleteValue(lineData);
                    }
                })

            })

        }

        // ======== 获取所有的院系 =============
        function loadQueryFacultys() {
            layui.use('form', function () {
                let form = layui.form;
                // 获取当前的下拉框容器
                let facultyContain = $('#q_faculty');
                // 清空
                facultyContain.empty();
                // 新建一个提示的
                $('<option>').attr('value', "").html("请选择").appendTo(facultyContain);
                // Ajax获取
                $.ajax({
                    url: "{% url 'list_faculty' %}",
                    method: 'post',
                    data: {
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.status) {
                            //遍历
                            $.each(res.data, (index, value) => {
                                // 使用jquery附加
                                $('<option>').attr('value', value.id).html(value.name).appendTo(facultyContain);
                            });
                            form.render();
                        } else {
                            layui.use('layer', function () {
                                let layer = layui.layer;
                                layer.msg(res.error, {
                                    icon: 2,
                                    area: ['360px', '180px'],
                                    time: -1,
                                    btn: ['取消']
                                })
                            })
                        }
                    }
                });


                // ==== 侦听 =====
                form.on('select(q_faculty)', function (obj) {
                    let faculty = obj.value;

                    // 获取当前的容器
                    let majorContain = $('#q_major');
                    // 清空
                    majorContain.empty();
                    // 新建一个提示的
                    $('<option>').attr('value', "").html("请选择").appendTo(majorContain);
                    // Ajax请求
                    $.ajax({
                        url: "{% url 'faculty_major' %}",
                        method: 'post',
                        data: {
                            faculty_id: faculty,
                            csrfmiddlewaretoken: "{{ csrf_token }}",
                        },
                        success: function (res) {
                            //遍历
                            $.each(res.data, (index, value) => {
                                // 使用jquery附加
                                $('<option>').attr('value', value.id).html(value.name).appendTo(majorContain);
                            });
                            form.render();
                        }
                    })
                });

                // === 侦听弹出层的院系的选择 -- 为添加生效！ =====
                form.on('select(faculty)', function (obj) {
                    // == Ajax== 根据院系获取该院系下的专业并填充到第二个下拉框
                    getMajorFormFaculty($('#faculty').val());
                })

            });

        }

        // ========= 所有的按钮点击 =============
        function buttonClick() {
            // === 查询 ===
            $('#btnQuery').on('click', function () {
                // 重新渲染表格
                initTable();
            });

            // === 显示全部===
            $('#btnAll').on('click', function () {
                location.reload();
            });

            // === 添加 ===
            $('#btnAdd').on('click', function () {
                // 修改Operation
                Operation = 1;
                // 加载弹出层
                loadLayer("添加学生");
            })

        }

        // =========== 展示弹出层 ==============
        function loadLayer(title, value = "") {

            let btns = ['确定', '取消'];
            // 判断是是不是查看详情
            if (Operation === 2) {
                btns = ['关闭'];
            }


            // layer
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>" + "【" + title + "】" + "</b>",
                    area: ['700px', '600px'],
                    offset: '50px',
                    btn: btns,
                    content: $('.layerArea'),
                    resize: false,

                    // ============success: 弹出层展示后自动执行的函数=========
                    success: function (index, layero) {

                        // 无论是添加、修改、还是查看详情，下拉框都要赋值 ！！！！
                        $.ajax({
                            url: "{% url 'list_faculty' %}",
                            method: 'get',
                            dataType: 'json',
                            success: function (res) {
                                let facultyContain = $('#faculty');
                                facultyContain.empty();
                                $('<option>').attr('value', "").text('请选择').appendTo(facultyContain);
                                // 使用jquery添加到下拉框中
                                if (res.status) {
                                    // 遍历
                                    $.each(res.data, (index, value) => {
                                        let item = $('<option>').attr('value', value.id).text(value.name);
                                        item.appendTo(facultyContain);
                                    });
                                    // 重新渲染
                                    form.render();

                                    // 如果是查看或者编辑，赋值
                                    if (Operation === 2 || Operation === 3) {
                                        console.log(value);
                                        // 赋值
                                        form.val('layerForm', value);
                                        form.val('layerForm', {
                                            faculty: value.faculty_id,
                                        });
                                        // 重新渲染
                                        form.render();

                                        // 加载专业
                                        getMajorFormFaculty(value.faculty_id, value.major_id);

                                    }
                                } else {
                                    layer.msg(res.error, {
                                        icon: 2,
                                        area: ['350px', '150px'],
                                        time: -1,
                                        btn: ['关闭']
                                    })
                                }
                            }
                        });

                        // 如果是修改 --- 学号不允许改  readonly --- disabled
                        if (Operation === 3) {
                            $('#sno').attr('readonly', true);
                        }
                        // 如果是查看，所有的都不允许改
                        if (Operation === 2) {
                            $('#layerForm').find('input, select').prop('disabled', true);
                        }


                    },

                    //=========== yes: 点击确认按钮后执行的函数-===============
                    yes: function (index, layero) {
                        // 恢复查看页面中关闭的功能
                        if (Operation === 2) {
                            // 关闭窗口
                            layer.close(index);
                        } else if (Operation === 1) {
                            // 添加
                            if (checkInput()) {
                                // 提交
                                $.ajax({
                                    url: "{% url 'add_student' %}",
                                    method: 'post',
                                    data: $('#layerForm').serialize(),
                                    dataType: 'json',
                                    success: function (res) {
                                        if (res.status) {
                                            location.reload();
                                        } else {
                                            layer.msg(res.error, {
                                                icon: 2,
                                                area: ['350px', '150px'],
                                                time: -1,
                                                btn: ['关闭'],
                                            })
                                        }
                                    }
                                })
                            }
                        } else if (Operation === 3) {
                            // 修改
                            if (checkInput()) {
                                // 提交
                                $.ajax({
                                    url: "{% url 'edit_student' %}",
                                    method: 'post',
                                    data: $('#layerForm').serialize(),
                                    dataType: 'json',
                                    success: function (res) {
                                        if (res.status) {
                                            location.reload();
                                        } else {
                                            layer.msg(res.error, {
                                                icon: 2,
                                                area: ['350px', '150px'],
                                                time: -1,
                                                btn: ['关闭'],
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    },

                    // =========== end: 关闭弹出层后表单的清理============
                    end: function (index, layero) {
                        // 只要关闭弹出层，所有的选择必须要初始化(空)
                        form.val('layerForm', {
                            sno: "",
                            name: "",
                            gender: "",
                            birthday: "",
                            mobile: "",
                            email: "",
                            address: "",
                            faculty: "",
                            major: "",
                            start_date: "",
                            status: "",
                        });
                        // 把学号的readonly取消
                        $('#sno').attr('readonly', false);

                        // 清除查看状态下所有的input，select 禁用
                        $('#layerForm').find('input, select').prop('disabled', false);
                    }

                })
            })
        }


        function getMajorFormFaculty(faculty_id, major_id = "") {

            layui.use('form', function () {
                let form = layui.form;
                $.ajax({
                    url: "{% url 'faculty_major' %}",
                    method: 'post',
                    data: {
                        faculty_id: faculty_id,
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    success: function (res) {
                        // 赋值
                        let majorContainer = $('#major');
                        // 清空
                        majorContainer.empty();
                        // 添加提示
                        $('<option>').attr('value', "").text("请选择").appendTo(majorContainer);
                        // 遍历
                        $.each(res.data, (index, value) => {
                            $('<option>').attr('value', value.id).text(value.name).appendTo(majorContainer);
                        });

                        // 赋值
                        form.val('layerForm', {
                            major: major_id,
                        });

                        form.render();
                    }
                })
            });

        }


        // ==============提交前的验证==========
        function checkInput() {
            // 清空所有
            $('.error-msg').text("");
            // 定义一个变量
            let checkResult = true;

            // 验证学号【7位整数】 -  如果验证不通过 checkResult = false
            let sno = $('#sno').val().trim();
            if (sno.match(/^\d{7}$/) == null) {
                checkResult = false;
                $('#sno').next().text("学号要求是7位长度的整数");
            }
            // 判断学号是否存在--仅添加
            if (Operation === 1) {
                $.ajax({
                    url: "{% url 'is_sno_exists' %}",
                    method: 'post',
                    data: {
                        sno: $('#sno').val().trim(),
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.data) {
                            checkResult = false;
                            $('#sno').next().text("学号已存在");
                        }
                    }
                })
            }

            // 验证姓名  - 如果验证不通过 checkResult = false
            let name = $('#name').val().trim();
            if (name.match(/^[\u4e00-\u9fa5]{2,5}$/) == null) {
                checkResult = false;
                $('#name').next().text("姓名必须是2-5个汉字");
            }

            // 验证手机号码  - 如果验证不通过 checkResult = false
            let mobile = $('#mobile').val().trim();
            if (mobile.match(/^[1]\d{10}$/) == null) {
                checkResult = false;
                $('#mobile').next().text("手机必须要是11位数字");
            }

            // 验证邮箱地址 -  如果验证不通过 checkResult = false
            let email = $('#email').val().trim();
            if (email.match(/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/) == null) {
                checkResult = false;
                $('#email').next().text("邮箱地址不符合格式要求");
            }

            // 验证家庭住址 - 如果验证不通过 checkResult = false
            if ($('#address').val().trim().length == 0) {
                checkResult = false;
                $('#address').next().text("家庭地址不能为空！");
            }

            return checkResult

        }

        // ============= 删除学生  ================
        function deleteValue(value) {
            //确认的提示
            let confirmStr = "您确认删除学生信息【" + value.sno + "-" + value.name + "】信息吗？";
            // 确认
            layui.use('layer', function () {
                layer.confirm(confirmStr, {icon: 3, area: ['450px', '200px']}, function (index) {
                    // ajax
                    $.ajax({
                        url: "{% url 'del_student' %}",
                        method: "post",
                        data: {
                            sno: value.sno,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.status) {
                                location.reload();
                            } else {
                                layer.msg(res.error, {
                                    icon: 2,
                                    area: ['350px', '150px'],
                                    time: -1,
                                    btn: ['关闭']
                                });
                            }
                        }
                    })
                })
            })
        }


    </script>
{% endblock %}

<!--
 同一个弹出层，三种状态加载：
 1. 查看 ---  标题：查看学生信息  特点：填充当前数据到表单， 所有的都是只读，不允许修改   按钮：关闭按钮
 2. 添加 ---  标题：添加学生      特点：所有的表单为空，等待输入或者选择   按钮：保存、关闭
 3. 修改 ---  标题：修改学生信息   特点：填充当前数据到表单，学号只读，其他都可以修改， 按钮：保存、关闭
-->
